package com.tocmat;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.log4j.Logger;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * ftpserver-1.0.6.zip<a href=
 * "http://mirrors.hust.edu.cn/apache/mina/ftpserver/1.0.6/dist/ftpserver-1.0.6.zip"
 * >download</a>
 * <hr>
 * 
 * @author Administrator
 *
 */
public class FtpLauncher {
	Logger logger = Logger.getLogger(FtpLauncher.class);

	public static void main(String[] args) throws FtpException {
		FtpLauncher launcher = new FtpLauncher();
		
		FtpServer server = null;
		String path = launcher.getClass().getResource("/").getPath();
		server = launcher.newFtpServer(path+"ftp/ftpd-typical.xml");

		if (server == null) {
			server = launcher.newFtpServer(2121);
		}

		server.start();
	}

	public FtpServer newFtpServer(int port) {
		FtpServerFactory serverFactory = new FtpServerFactory();
		ListenerFactory factory = new ListenerFactory();
		// set the port of the listener
		factory.setPort(port);
		Listener listener = factory.createListener();
		// replace the default listener
		serverFactory.addListener("default", listener);
		// UserManager userManager = userManager
		// serverFactory.setUserManager(userManager);
		// start the server
		FtpServer server = serverFactory.createServer();
		return server;
	}

	public FtpServer newFtpServer(String xmlConfigLocation) {
		// org.apache.ftpserver.main.CommandLine
		FtpServer server = null;
		FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
				xmlConfigLocation);
		if (ctx.containsBean("server")) {
			server = (FtpServer) ctx.getBean("server");
		} else {
			String[] beanNames = ctx.getBeanNamesForType(FtpServer.class);
			if (beanNames.length == 1) {
				server = (FtpServer) ctx.getBean(beanNames[0]);
			} else if (beanNames.length > 1) {
				System.out
						.println("Using the first server defined in the configuration, named "
								+ beanNames[0]);
				server = (FtpServer) ctx.getBean(beanNames[0]);
			} else {
				System.err
						.println("XML configuration does not contain a server configuration");
			}
		}
		ctx.close();
		return server;
	}

}
